package com.qinge.blog.security;

import com.qinge.blog.entity.BlogUser;
import com.qinge.blog.utils.jwt.JwtUtil;
import com.qinge.blog.utils.redis.RedisUtil;
import io.jsonwebtoken.Claims;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author QDW
 * @date 2022/5/7 11:46
 * @description LogoutHandler实现类
 **/
@Component
public class LogoutHandlerImpl implements LogoutHandler {

    @Resource
    private RedisUtil redisUtil;

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        // 获取token
        String token = request.getHeader("token");

        // 解析token
        String userId;

        if(Objects.isNull(token)|| "null".equals(token) || !JwtUtil.isSigned(token)){
            return;
        }else{
            Claims claims = JwtUtil.parseJWT(token);
            userId = claims.getSubject();
        }

        // 删除redis中的值
        redisUtil.deleteObject("login:" + userId);
    }
}
